#!/bin/bash
export LANG="en_US.UTF-8"
if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash hmmer-3.3.2.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
yum install -y  environment-modules csh time patch libatomic perl-Data-Dumper autoconf automake libtool numactl binutils systemd-devel valgrind flex wget

set -e
wget -t 10 -c -P $buildpath https://github.com/EddyRivasLab/hmmer/archive/refs/heads/h3-arm.zip
unzip $buildpath/h3-arm.zip -d $buildpath
cd $buildpath/hmmer-h3-arm/
wget -t 10 -c https://github.com/EddyRivasLab/easel/archive/refs/heads/master.zip
unzip master.zip
mv easel-master/ easel/
autoconf
export MPICC=mpicc
export MPICXX=mpicxx
export MPIFC=mpifort

./configure --prefix=$installpath/hmmer-3.3.2 --enable-mpi --enable-neon CC=$MPICC CXX=$MPICXX FC=$MPIFC F77=$MPIFC
sed -i 's/esl_FCompare/esl_FCompareNew/g' src/p7_domain.c
sed -i 's/esl_DCompare/esl_DCompareNew/g' src/p7_domain.c
sed -i 's/esl_FCompare/esl_FCompareNew/g' src/p7_hit.c
sed -i 's/esl_DCompare/esl_DCompareNew/g' src/p7_hit.c

sed -i 's/esl_FCompare_old/esl_FCompare/g' src/p7_hmm.c
sed -i 's/esl_FCompare_old/esl_FCompare/g' src/p7_trace.c
sed -i 's/esl_FCompare_old/esl_FCompare/g' src/impl_neon/p7_oprofile.c
sed -i 's/esl_FCompare_old/esl_FCompare/g' src/generic_vtrace.c
sed -i 's/esl_FCompare_old/esl_FCompare/g' src/p7_bg.c
sed -i 's/esl_FCompare_old/esl_FCompare/g' src/p7_gmx.c

sed -i '41 d' src/impl_neon/impl_neon.h
sed -i '29c static inline float' src/impl_neon/impl_neon.h
sed -i 's/esl_FCompare_old/esl_FCompare/g' src/./generic_stotrace.c
sed -i 's/esl_FCompare_old/esl_FCompare/g' src/./generic_viterbi.c
sed -i 's/esl_FCompare_old/esl_FCompare/g' src/./modelconfig.c
sed -i 's/esl_FCompare_old/esl_FCompare/g' src/impl_neon/./stotrace.c
sed -i 's/esl_FCompare_old/esl_FCompare/g' src/impl_neon/./optacc.c
make -j$(nproc)
make check
make -j$(nproc) install

mkdir -p $installpath/hmmer-3.3.2 && cp -r $buildpath/hmmer-h3-arm/* $installpath/hmmer-3.3.2

rm -rf $buildpath/hmmer-3.3.2
cat>"$installpath/hmmer-3.3.2/hmmer_modulefiles"<<EOF
#%Module1.0
conflict hmmer
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
        set modfile_path [file dirname \$modfile]
	    return \$modfile_path
    }
set pwd [getModulefileDir]
set HMMER \$pwd
setenv HMMER \$HMMER
prepend-path PATH \$HMMER/bin
EOF
